var MyCart = {
	data:[],
	reload : function(){
		var _t = this;
		$.ajax({
			url: HOST + "/store/cart/cart_init.jhtml",
			type: "GET",
			data: {
			},
			dataType: "json",
			async:false,
			cache: false,
			success: function(data) {
				_t.initHTML(data);
				_t.data = data;
				/*加载HTML数量*/
				_t.updateCartTotalCount();
			}
		});
	},
	updateCartTotalCount : function(){
		var cartTotalCount = 0;
		if($("div[cartempty=cartempty]").is(":hidden")){
			$("input[quantity=quantity]").each(function(){
				cartTotalCount += parseInt($(this).val());
			});
		}
		$("#i_cart_total").html(cartTotalCount);
	},
	toBuy:function(){
		if(!this.data.isValid)
		{
			var dlgx = $.dialog({
				width:440,
				title:"确认提示",
				content: "商品信息发生变更了,请重新选择",
				ok: "确定",
				cancel: null,
				autoClose:true,
				onOk: function() {
				}
			}); 
		}
		else
		{
				$.ajax({
					url: HOST +"/login/login_info.jhtml",
					type: "POST",
					data: {},
					dataType: "json",
					cache: false,
					success: function(result) {
						if(result.v)
						{
							window.location.href=HOST + "/store/order/buy.jhtml?bean.from=cart";
						}
						else
						{
							var url = HOST + "/login/tologin.jhtml?redirect=" + encodeURIComponent(window.location.href);
							window.location.href= url;
						}
					}
				});
		}
	},
	processData:function(data)
	{
		if(data != null && data != "" && data.products != null){
			for ( var i = 0; i < data.products.length; i++ )
			{
				var gift_total = 0 ;
				
				if(data.products[i].giftlist)
				{
					for ( var j in data.products[i].giftlist)
					{
						gift_total = gift_total + data.products[i].giftlist[j].price ;
					}
				}
				data.products[i].product.price = data.products[i].product.price + gift_total;
			}
			return data;
		}
	},
	initHTML:function(data)
	{
		data =this.processData(data);
		if(data.products.length==0)
		{
			$("div[cartcontext=cartcontext]").hide();
			$("div[cartempty=cartempty]").show();	
		}
		else
		{
			$("#mycart").html("");
			$("#mycart_tmpl").tmpl(data).appendTo('#mycart');
			this.initEvents();
		}
	},
	initEvents: function()
	{
		var $quantity = $("input[quantity=quantity]");
		var $incinput = $("span[incinput=incinput]");
		var $decinput = $("span[decinput=decinput]");
		var $delete = $("span[delinput=delinput]");
		var $delservice = $("span[delservice=delservice]");
		
		// 数量
		$quantity.keypress(function(event) {
			var key = event.keyCode ? event.keyCode : event.which;
			if ((key >= 48 && key <= 57) || key==8) {
				return true;
			} else {
				return false;
			}
		});
		
		// 数量
		$quantity.change(function() {
			var pid = $(this).attr("data-pid");
			var skuid = $(this).attr("data-skuid");
			var max = $(this).attr("data-max");
			var quantity = $(this).val();
			if (/^\d*[1-9]\d*$/.test(quantity)) {
				/*if(quantity <= parseInt(max) )*/
				Cart.add(pid,skuid,quantity,function(){MyCart.reload()});
			}
			
		});
		
		// 增加数量
		$incinput.click(function() {
			var $quantity = $(this).parent().find("input[quantity=quantity]");
			var $error = $(this).parent().parent().find(".limit-num");
			var quantity = $quantity.val();
			if (/^\d*[1-9]\d*$/.test(quantity)) {
				var n = parseInt(quantity) + 1;
				if(n <= $quantity.attr("data-max") && n <= $quantity.attr("data-ruleCount"))
				{
					$quantity.val(parseInt(quantity) + 1);
					$quantity.trigger("change");
					$(this).attr("disabled","disabled"); 
				}
				else
				{ 
					if($quantity.attr("data-isvalid")=="false")
					{
						var type =$quantity.attr("data-context");  
						if("NOT_ENOUGH_STOCK"==type)
						{
							$error.html("库存不足" ).show();
						}
						else if("PRODUCT_DOWN"==type || "PRODUCT_UN_UP"== type)
						{
							$error.html("产品已下架" ).show();
						}
						else if("NULL"==type)
						{
							$error.html("已失效" ).show();
						}
						else if("NUMBER_IS_SO_MUCH"==type)
						{
							$error.html("限购" + $quantity.attr("data-ruleCount") +"件").show();
						}
						else if("PARAMETERS_ERROR"==type)
						{
							$error.html("参数错误").show();
						}
						else{
							$error.html("错误").show();
						}
					}
					else
					{
						if(n > $quantity.attr("data-ruleCount")){
							$error.html("限购" + $quantity.attr("data-ruleCount") +"件").show();
						} else{
							$error.html("库存不足" ).show();
						}
					}
				}
			} else {
					$quantity.val(1);
			}
		});
		// 减少数量
		$decinput.click(function() {
			var $quantity = $(this).parent().find("input[quantity=quantity]");
			var quantity = $quantity.val();
			if (/^\d*[1-9]\d*$/.test(quantity) && parseInt(quantity) > 1) {
				$quantity.val(parseInt(quantity) - 1);
				$quantity.trigger("change");
				$(this).attr("disabled","disabled");
			} else {
				$quantity.val(1);
			}

		});
		// 减少数量
		$delete.click(function() {
			var $this = $(this);
			$.dialog({
				width:440,
				title:"确认提示",
				content: "确认要删除该商品吗？",
				ok: "确定",
				cancel: "取消",
				onOk: function() {
					var pid = $this.parent().parent().parent().find("input[quantity=quantity]").attr("data-pid");
					var skuid =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-skuid");
					var count =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-count");
					var skuname =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-skuname");
					var dataprice =$this.parent().parent().parent().find("span[quantity=quantity]").attr("data-price");
					var skunumber =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-skunumber");
					var categoryid =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-categoryid");
					var categoryname =$this.parent().parent().parent().find("input[quantity=quantity]").attr("data-categoryname");
					Cart.remove(pid,skuid,count,skuname,dataprice,skunumber,categoryid,categoryname,function(){MyCart.reload()});
				}
			}); 
		});
		//删除服务商品
		$delservice.click(function() {
			var $this = $(this);
			$.dialog({
				width:440,
				title:"确认提示",
				content: "确认要删除该商品吗？",
				ok: "确定",
				cancel: "取消",
				onOk: function() {
					var proids = [];
					var serviceids = [];
					var pid = $this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-pid");
					var skuid =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-skuid");
					var count =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-count");
					var skuname =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-skuname");
					var dataprice =$this.parent().parent().parent().parent().find("span[quantity=quantity]").attr("data-price");
					var skunumber =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-skunumber");
					var categoryid =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-categoryid");
					var categoryname =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-categoryname");
					var promoationids =$this.parent().parent().parent().parent().find("input[quantity=quantity]").attr("data-promoids");
					if(promoationids != null && promoationids != "-1" && promoationids != ""){
						proids.push(promoationids);
					}
					var $delserviceBtn = $this.parent().parent().parent().find(".delete-btn[delservice=delservice]");
					if($delserviceBtn.length > 0){
						var currserviceId = $this.attr("data-serviceid");
						$delserviceBtn.each(function(){
							var serviceSkuId = $(this).attr("data-serviceid");
							if(currserviceId != serviceSkuId){
								serviceids.push(serviceSkuId);
							}
						});
					}
					Cart.add_number(pid,skuid,0,proids,serviceids,0,function(){MyCart.reload()});
				}
			}); 
		});
	}
}

function xn_cart(){
	/*初始化小能咨询所需参数 begin*/
	var ntalkerparam = {cartprice:$("#total_fee").val()};
	var items = []; 
	$(".cart_json_data").each(function(index, item){
		var cart_json_data = $.parseJSON($(this).val());
		items.push(cart_json_data);
	});
	ntalkerparam.items = items;
	webChat.cart(ntalkerparam);
	/*初始化小能咨询所需参数 end*/
}

$(document).ready(function(){
	MyCart.reload();
	if(typeof(webChat) != "undefined"){
		xn_cart();
	}
})